import NavigationUtil from "@/navigator/NavigationUtil";
import RouterConstant from "@/navigator/RouterConstant";
import { ArrayUtil } from "@theling/utils";
import { industryCategoryList } from "./rjrUtils";

/**
 * 当前页是否是最后一页
 * @param data
 */
export const isLastPageData = (data: any) => {
  if (Object.keys(data).length > 0) {
    // 判断当前数据是否是最后一条
    const { records, current } = data;
    // 如果当前只有一条数据了并且当前页数大于一页
    return records.length === 1 && current > 1;
  }
  return false;
};

/**
 * 判断是否有更多的数据
 * @param data 返回的分页数据
 * @param config 配置信息
 */
export const haveMorePage = (data: any, config: any) => {
  // 判断下，当前页面是不是等于data
  if (config.pageNum === data.pages) {
    return false;
  }
};
// 获取二维码的url
export const getUrlParams = (url: string) => {
  if (!url && window) {
    url = window.location.href;
  }
  const theRequest: any = {};
  if (url.includes("#")) {
    url = url.split("#")[1];
  }
  if (url.includes("?")) {
    const str = url.split("?")[1];
    const strs = str.split("&");
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
    }
  }
  return theRequest;
};
/*
 * 版本号比较方法
 * 传入两个字符串，当前版本号：curV；比较版本号：reqV
 * 调用方法举例：compare("1.1","1.2")，将返回false
 */
export const compareVer = (curV: string, reqV: string) => {
  if (curV && reqV) {
    if (curV === reqV) {
      return true;
    }
    // 将两个版本号拆成数字
    const arr1 = curV.split(".");
    const arr2 = reqV.split(".");
    const minLength = Math.min(arr1.length, arr2.length);
    let position = 0;
    let diff = 0;
    // 依次比较版本号每一位大小，当对比得出结果后跳出循环（后文有简单介绍）
    while (
      position < minLength &&
      (diff = parseInt(arr1[position]) - parseInt(arr2[position])) === 0
    ) {
      position++;
    }
    diff = diff !== 0 ? diff : arr1.length - arr2.length;
    // 若curV大于reqV，则返回true
    return diff > 0;
  } else {
    // 输入为空
    console.log("版本号不能为空");
    return false;
  }
};

/**
 * 判断条目是否是许可
 */
export const isPermissionItem = (item: any) => {
  const permitType = Number(item.permitType);
  if (permitType === 0) {
    return false;
  }
  if (permitType === 5) {
    return false;
  }
  return permitType !== 4;
};

/**
 * 生成条目的标签
 * @param item
 * @returns
 */
export const buildItemTag = (item: any) => {
  let title = "一般事项";
  const permitType = Number(item.permitType);
  switch (permitType) {
    case 0:
    case 5:
      return (title = "一般事项");
    case 1:
      return (title = "前置许可");
    case 2:
      return (title = "后置许可");
    case 3:
      return (title = "许可事项");
    case 4:
      return (title = "一般事项（需备案）");
    // case 5:
    //   return (title = "许可事项（部分地方）");
    case 6:
      return (title = "负面清单事项");
  }
};

/**
 * 生成许可或一般的字符串
 * @param selectList
 * @param limitSelectKeyList
 */
function buildPerOrGenStr(selectList: any, limitSelectKeyList: any) {
  return selectList
    .map((item: any, index: number) => {
      if (index === selectList.length - 1) {
        return (
          item.standardItem +
          (limitSelectKeyList.indexOf(item.scopeId) > -1
            ? "【分支机构经营】"
            : "") +
          "。"
        );
      } else {
        return (
          item.standardItem +
          (limitSelectKeyList.indexOf(item.scopeId) > -1
            ? "【分支机构经营】"
            : "") +
          "；"
        );
      }
    })
    .join("");
}

/**
 * 字符串是否过长
 */
export const isLongStr = (resultData: any, values: any) => {
  // 判断旧的数据
  if (Array.isArray(values)) {
    const addStr = values.map((item) => item.standardItem).join("；");
    return (
      resultData.genStr.length + resultData.perStr.length + addStr.length > 1000
    );
  } else {
    return (
      resultData.genStr.length +
        resultData.perStr.length +
        values.standardItem.length >
      1000
    );
  }
};

/**
 * 生成国标选择
 * @param gbObjList 国标的数组
 * @param superclass 父元素，进行国标限制
 * @param il
 */
export const buildGbSelectList = (
  gbObjList: any,
  superclass: any,
  il = "4" as any,
) => {
  il = Number(il);
  let newGbObjList = [];
  if (typeof gbObjList === "string") {
    // 1位的话，要取数组，虽然现在不支持1位，但是提前判断先
    let verParent = [];
    if (superclass) {
      if (superclass.length === 1) {
        // 得到大类的数组
        verParent = industryCategoryList[superclass];
      } else {
        verParent = [superclass];
      }
    }
    // 转成正则，这个正则，是用来判读是否以某个指定字符串开头的，测试代码：new RegExp("^12|^13.*$").test(1123)
    const regVerParent = new RegExp(`^${verParent.join("|^")}.*$`);
    newGbObjList = JSON.parse(gbObjList).filter((item: any) => {
      // 如果显示全部的，那么就只判断父级
      if (il === -1 && superclass && superclass.length === 1) {
        return regVerParent.test(item.code);
      }
      if (il === -1) {
        return regVerParent.test(item.code);
      }
      // 对长度进行过滤
      return regVerParent.test(item.code) && item.code.length === il;
    });
  }
  return newGbObjList;
};

export const buildIndustryObj = (
  state: any,
  selectList: any,
  urlParams: any,
) => {
  // 只对首次添加做判断
  state.industryList = buildGbSelectList(
    selectList[0].gbObjList,
    urlParams.superclass,
    urlParams.il,
  );
  if (state.industryList.length === 1) {
    state.industryModal = false;
    state.industry = {
      code: state.industryList[0].code,
      name: state.industryList[0].name,
    };
  } else {
    state.industry = { code: "", name: "请添加条目选择行业" };
  }
  return state;
};

/**
 * 判断哪个应该在前面
 * @param forceIdItem
 * @param selectList
 * @param firs
 */
export const whoIsFirst = ({
  forceIdItem = {} as any,
  selectList,
  first,
}: any) => {
  // 如果强制绑定
  if (forceIdItem.scopeId) {
    if (forceIdItem.isForce) {
      return isPermissionItem(forceIdItem) ? "per" : "gen";
    }
  } else if (selectList[0]) {
    // 没有强制绑定，则以第一个为准
    return isPermissionItem(selectList[0]) ? "per" : "gen";
  }
  if (first) {
    return first;
  }
  return "per";
};

export const addScopeItemToList = ({
  values,
  type,
  selectList,
  selectKeyList,
  perSelectList,
  genSelectList,
  first,
  sort = true,
  addItem,
}: any) => {
  let newValue = [];
  if (type) {
    // 如果全选，去除已经选好了的
    newValue = values.filter(
      (item: any) => selectKeyList.indexOf(item.scopeId) === -1,
    );
    // 提取出许可项目
    newValue.forEach((item: any) => {
      if (isPermissionItem(item)) {
        perSelectList.push(item);
      } else {
        genSelectList.push(item);
      }
    });
  } else if (isPermissionItem(values)) {
    perSelectList.push(values);
  } else {
    genSelectList.push(values);
  }
  const noApplyList = selectList.filter(
    (item: any) => item.entApply === false || item.apply === false,
  );
  if (sort) {
    if (first === "per") {
      selectList = [...perSelectList, ...genSelectList, ...noApplyList];
    } else {
      selectList = [...genSelectList, ...perSelectList, ...noApplyList];
    }
  } else if (Array.isArray(values)) {
    selectList = selectList.concat(newValue);
  } else {
    selectList.push(values);
  }
  selectKeyList = selectList.map((item: any) => item.scopeId);
  return {
    selectList,
    selectKeyList,
    perSelectList,
    genSelectList,
    addItem,
  };
};

/**
 * 生成结果数据
 * @param searchType 查询方式
 * @param perSelectList 许可项目
 * @param genSelectList 一般项目
 */
// 许可后缀
const perSuffix =
  "（依法须经批准的项目，经相关部门批准后方可开展经营活动，具体经营项目以相关部门批准文件或许可证件为准）";
// 一般后缀
const genSuffix = "（除依法须经批准的项目外，凭营业执照依法自主开展经营活动）";
export const buildResultData = ({
  perSelectList,
  genSelectList,
  limitSelectKeyList = [],
  first,
}: any) => {
  // 许可
  let perStr = buildPerOrGenStr(perSelectList, limitSelectKeyList);
  // 一般
  let genStr = buildPerOrGenStr(genSelectList, limitSelectKeyList);
  const perExist: any = perStr.length > 0;
  const genExist: any = genStr.length > 0;
  // 生成数据
  let resStr;
  let one = "gen";
  let two = "per";
  if (first === "gen") {
    one = "gen";
    two = "per";
    // 一般在前
    resStr =
      (genExist ? "一般项目：" + genStr + genSuffix : "") +
      (perExist ? "许可项目：" + perStr + perSuffix : "");
  } else {
    one = "per";
    two = "gen";
    // 许可在前
    resStr =
      (perExist ? "许可项目：" + perStr + perSuffix : "") +
      (genExist ? "一般项目：" + genStr + genSuffix : "");
  }
  return {
    genStr,
    genExist,
    perExist,
    perStr,
    resStr,
    one,
    two,
  };
};

/**
 * 移除条目的方法
 */
export const searchRemoveByIndex = ({
  index,
  selectList,
  selectKeyList,
  perSelectList,
  genSelectList,
  limitSelectList,
  limitSelectKeyList,
  noApplyList,
  masterSelectList,
}: any) => {
  // 得到下标的数据
  const item = selectList[index];
  let newPerList: any = [],
    newGenList: any = [];
  // 移除列表数据
  selectList.splice(index, 1);
  selectKeyList.splice(index, 1);
  // 判断是否有限分支机构
  if (Array.isArray(limitSelectKeyList)) {
    const limitIndex = limitSelectKeyList.indexOf(item.scopeId);
    if (limitIndex >= 0) {
      limitSelectList.splice(limitIndex, 1);
      limitSelectKeyList.splice(limitIndex, 1);
    }
  }
  // 移除许可跟非许可里面的
  if (isPermissionItem(item)) {
    newPerList = ArrayUtil.remove(perSelectList, item, "scopeId");
    newGenList = genSelectList;
  } else {
    newGenList = ArrayUtil.remove(genSelectList, item, "scopeId");
    newPerList = perSelectList;
  }
  if (Array.isArray(masterSelectList) && masterSelectList.length > 0) {
    masterSelectList =
      ArrayUtil.remove(masterSelectList, item, "scopeId") || [];
    // 判断下是否移除了全部
    if (masterSelectList.length === 0) {
      uni.showModal({
        title: "提示",
        content: "请选择一条可作为所选行业表述的主营条目，否则无法生成组合码",
      });
    }
  }
  // 移除不适用里面的
  const newNoApplyList = ArrayUtil.remove(noApplyList, item, "scopeId");
  // 生成结果
  const resultData = buildResultData({
    genSelectList,
    perSelectList,
    limitSelectKeyList,
  });
  return {
    perSelectList: newPerList,
    genSelectList: newGenList,
    noApplyList: newNoApplyList,
    limitSelectList,
    limitSelectKeyList,
    selectKeyList,
    selectList,
    masterSelectList,
    resultData,
  };
};

/**
 * 详情页分享配置
 */
export const detailShareOptions = (options: any) => ({
  title: "看看这个条目",
  path: `pages/details/details?scopeId=${options.scopeId}&ac=${options.ac}`,
});

/**
 * 反馈
 * @param userInfo
 * @returns
 */
export const toFeedbackHandler = (userInfo: any) => {
  // #ifdef MP-WEIXIN
  if (typeof userInfo !== "object") {
    uni.showToast({
      title: "请先登录",
      icon: "none",
    });
    return;
  }
  if (!userInfo.tucaoId) {
    uni.showToast({
      title: "请先登录",
      icon: "none",
    });
    return;
  }
  // #endif
  NavigationUtil.toPage(RouterConstant.TUCAO);
};
